package com.codeying.servlet.userComment;

import com.codeying.entity.LoginUser;
import com.codeying.entity.UserComment;
import com.codeying.servlet.AbsServlet;
import com.codeying.utils.CommonUtils;
import com.codeying.utils.MyUtils;
import com.codeying.utils.component.ApiResult;
import com.codeying.utils.component.QueryMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 获取评论列表
 * 评论
 */
@WebServlet("/userComment2/action")
public class CommentSerclet extends AbsServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setContentType("application/json; charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        //获取哪个内容的评论？
        String ctid = req.getParameter("ctid");
        //获取所有评论
        List<UserComment> comments = userCommentService.list(new QueryMap().add("ctid",ctid).add("orderby","id desc").add("status","正常"));
        resp.getWriter().print(ApiResult.successData(comments));
    }

    /**
     * 评论
     * @param req
     * @param resp
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws  IOException {
        req.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        resp.setContentType("application/json; charset=utf-8");
        resp.setCharacterEncoding("UTF-8");
        LoginUser loginUser = MyUtils.getUser(req);
        if(loginUser == null){
            resp.getWriter().print(ApiResult.fail("请先登录！"));//跳转登录
            return;
        }
        UserComment comment = new UserComment();
        comment.setId(CommonUtils.newId());
        comment.setUserid(loginUser.getId());
        comment.setUsername(loginUser.getUsername());
        comment.setRolech(loginUser.getRolech());
        comment.setContent(req.getParameter("content"));//获取评论内容
        comment.setCtid(Integer.parseInt(req.getParameter("cid")));//获取内容id
        comment.setType(req.getParameter("type"));//获取内容类型
        comment.setCreatetime(new Date());
        comment.setStatus("正常");
        //保存内容
        userCommentService.insert(comment);
        resp.getWriter().print(ApiResult.success());
    }
}
